package com.zzp.sms.security.config;

import com.zzp.sms.security.filter.PhoneNumAuthenticationFilter;
import com.zzp.sms.security.handler.CustomizeAuthenticationFailureHandler;
import com.zzp.sms.security.handler.CustomizeAuthenticationSuccessHandler;
import com.zzp.sms.security.provider.DaoPhoneNumAuthenticationProvider;
import com.zzp.sms.security.service.UserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 佐斯特勒
 * <p>
 *  该类的作用是将 自定义Filter与Provider串起来，然后加入spring security的整个过滤器链中
 * </p>
 * @version v1.0.0
 * @date 2020/1/13 0:41
 * @see  SmsCodeAuthenticationConfig
 **/
@Component
public class SmsCodeAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    /**
     * 失败认证处理
     */
    @Resource
    private CustomizeAuthenticationFailureHandler authenticationFailureHandler;

    /**
     * 成功认证处理
     */
    @Resource
    private CustomizeAuthenticationSuccessHandler authenticationSuccessHandler;

    /**
     * 用户详情服务--此处是认证
     */
    @Resource
    private UserDetailsService userDetailsService;

    /**
     * 将Filter与Provider串起来
     * @param http http安全请求
     * @throws Exception 异常
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        var phoneNumAuthenticationFilter = new PhoneNumAuthenticationFilter();

        // 设置AuthenticationManager, 设置目的是 使用它来协调 Filter与Provider
        phoneNumAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //使用手机号登录失败了如何处理
        phoneNumAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);

        // 使用手机号登录成功了如何处理
        phoneNumAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);

        var daoPhoneNumAuthenticationProvider = new DaoPhoneNumAuthenticationProvider();
        daoPhoneNumAuthenticationProvider.setUserDetailsService((UserDetailsServiceImpl) userDetailsService);

        // 设置Provider以及过滤器
        http.authenticationProvider(daoPhoneNumAuthenticationProvider)
                .addFilterAfter(phoneNumAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
